package com.firepongo.chaos.model.service.alibaba;

import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.firepongo.chaos.model.dto.DTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AliMessageService {
    private static String accessId;
    private static String accessSecret;
    private static String accessSignName;

    @Value("${app.ali.sms.access.key.id:}")
    private void setAccessId(String id) {
        accessId = id;
    }

    @Value("${app.ali.sms.access.key.secret:}")
    private void setAccessSecret(String secret) {
        accessSecret = secret;
    }

    @Value("${app.ali.sms.access.key.signName:}")
    private void setSignName(String signName) {
        accessSignName = signName;
    }

    private static com.aliyun.dysmsapi20170525.Client client = null;

    public com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "dysmsapi.aliyuncs.com";
        try {
            return new com.aliyun.dysmsapi20170525.Client(config);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public SendSmsResponseBody sendSms(String phoneNumbers, String templateCode, DTO templateParam) {
        if (client == null) {
            client = createClient(accessId, accessSecret);
        }
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNumbers)
                .setTemplateCode(templateCode)
                .setSignName(accessSignName)
                .setTemplateParam(JSONUtil.toJsonStr(templateParam));

        try {
            return client.sendSms(sendSmsRequest).body;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }


}
